package sync

import (
	"SSO/models"
	"SSO/tools"
	"encoding/json"
	"fmt"
	"github.com/gomodule/redigo/redis"
)

type User struct {}

type SyncUserInfo struct {
	Operate 	string
	Key 		map[string]interface{}
	Data 		struct{
		Id 		int
		Name	string
		NamePy	string `json:"name_py"`
		Sex 	int
		Tel 	string
		Email 	string
	}
}

func (User) SyncUser()  {
	go func() {
		fmt.Println(111)
		c := tools.GetRedisClient().Get()
		if c == nil {
			fmt.Println("获取redis连接失败")
			return
		}
		psc := redis.PubSubConn{Conn: c}
		psc.Subscribe("user")
		for {
			switch v := psc.Receive().(type) {
			case redis.Message:
				userInfo := &SyncUserInfo{}
				err := json.Unmarshal(v.Data, userInfo)
				if err != nil {
					fmt.Printf("%s data[%s]", err.Error(), v.Data)
					return
				}
				if userInfo.Operate == "create" {
					password := userInfo.Data.Tel[5:]
					fmt.Println(userInfo.Data.NamePy, password)
					_, err = models.Users{}.Create(userInfo.Data.NamePy, password)
				}else if userInfo.Operate == "delete" {
					err = models.Users{}.Delete(userInfo.Data.NamePy)
				}

				if err != nil {
					fmt.Printf("%s data[%v]", err.Error(), userInfo)
				}
				//fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
			case redis.Subscription:
				fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
			case error:
				fmt.Printf("%v", v)
			}
		}
	}()
}